package top.yifengxiner.blockchain.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.yifengxiner.blockchain.pojo.vo.BRegisterBody;
import top.yifengxiner.blockchain.service.BRegisterService;
import top.yifengxiner.common.core.pojo.AjaxResult;
import top.yifengxiner.common.core.pojo.entity.SysUser;
import top.yifengxiner.common.utils.ShiroUtils;
import top.yifengxiner.framework.shiro.service.SysPasswordService;
import top.yifengxiner.system.mapper.SysUserMapper;
import top.yifengxiner.system.service.SysUserService;

import java.util.List;

/**
 * @author ：baixiao
 * @date ：Created in 2021/5/12 10:01
 * @description：注册服务
 * @modified By：
 * @version: 0.0.1$
 */
@Service
public class BRegisterServiceImpl implements BRegisterService
{

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysUserMapper userMapper;

    @Override
    public AjaxResult register(BRegisterBody registerBody)
    {
        if(registerBody.getSubject()== null)
        {
            return AjaxResult.warn("主体为空");
        }
        if(registerBody.getPassword() == null)
        {
            return AjaxResult.warn("密码为空");
        }

        List<SysUser> user2 = userMapper.selectList(new QueryWrapper<SysUser>());
        for(SysUser user1 : user2)
        {
            if(registerBody.getSubject().equals(user1.getUserName()))
            {
                return AjaxResult.error("用户名已存在");
            }
        }

        SysUser user = new SysUser();
        user.setUserName(registerBody.getSubject());
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(registerBody.getSubject(),registerBody.getPassword(),user.getSalt()));
        boolean res = userService.registerUser(user);
        if(res)
        {
            return AjaxResult.success("注册成功");
        }
        return AjaxResult.error("注册失败");
    }
}
